package models

import (
	"errors"
	"time"
)

type Banner struct {
	Id        int       `json:"id"`
	Title     string    `json:"title"`
	Images    string    `json:"images"`
	Url       string    `json:"url"`
	Sort      int       `json:"sort"`
	CreatedAt time.Time `json:"created_at"`
}

func AddBanner(data map[string]interface{}) error {
	m := DB.Table("app_banner").Create(&Banner{
		Title:     data["title"].(string),
		Images:    data["images"].(string),
		Url:       data["url"].(string),
		Sort:      data["sort"].(int),
		CreatedAt: time.Now(),
	})
	if m.Error != nil {
		return errors.New(m.Error.Error())
	}

	return nil
}
func GetBanners(page, limit int) (interface{}, *Paginator) {
	var res []*Banner
	m := DB.Table("app_banner").Order("sort ASC")

	var count int
	m.Count(&count)
	paginate := NewPage(page, limit, count)

	err := m.Offset(paginate.Offset).Limit(paginate.Limit).Find(&res).Error
	if err != nil {
		return nil, nil
	}

	return res, &paginate
}
func GetBanner(id int) (banner Banner) {
	DB.Table("app_banner").Where("id = ?", id).First(&banner)
	return
}
func ExistBannerByID(id int) bool {
	var banner Banner
	DB.Table("app_banner").Select("id").Where("id = ?", id).First(&banner)

	if banner.Id > 0 {
		return true
	}

	return false
}

func EditBannerByID(id int, data interface{}) bool {
	err := DB.Table("app_banner").Where("id = ?", id).Updates(data)
	if err.Error != nil {
		return false
	}
	return true
}

func DeleteBanner(id int) bool {
	err := DB.Table("app_banner").Where("id = ?", id).Delete(Banner{})

	if err.Error != nil {
		return false
	}
	return true
}
